package gbench.appdemo.mall.appitf.formula;

import static gbench.common.tree.LittleTree.Term.FT;

import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import gbench.common.matlib.MatlibCanvas;
import gbench.common.matlib.MatlibCanvas.NVec;
import gbench.common.tree.LittleTree.IRecord;

@RestController
@RequestMapping("formula")
public class FormulaController {
    
    /**
     * 
     * @param line 文本命令
     * @param mode 语言的模式
     * @return
     */
    @RequestMapping("latex")
    public ModelAndView latex(final String line, final String mode) {
        String _line = null;
        if(mode==null) {
            _line = line;
        }else if(mode.equals("poly")) { // 多项式
            final var ss = line.split("[,\\s]+");
            MatlibCanvas.println(ss);
            final var n = IRecord.obj2num.apply(ss[0]).intValue()+1; // 多项式的处理
            final var nvec = NVec.of(n,i->i);
            final var c = ss.length > 1 ? FT("\\$0", ss[1]) : "c"; // 系数代号
            final var variable = ss.length > 2 ? FT("\\$0", ss[2]) : "x"; // 变量
            
            final var expression = nvec.fmap(i-> i==0?"1":FT("$0_{$2}$1^{$2}", c,variable,i.intValue()))
                .collect(Collectors.joining("+")); // 表达式
            _line=expression;
        }
        
        final ModelAndView mv = new ModelAndView();
        mv.addObject("line",_line);
        mv.setViewName("mall/latex");
        return mv;
    }

}
